#pragma once
#include <iostream>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <unordered_map>
#include "err.hpp"
#include "RingQueue.hpp"
#include "lockGuard.hpp"
#include "Thread.hpp"

namespace jrg
{

    const static uint16_t default_port = 8080;
    using func_t = std::function<std::string(std::string)>;
    class UdpServer
    {
    private:
        int sock_;
        uint16_t port_;
        // std::string ip_; 在云服务器上不需要手动绑定ip,系统会默认绑定,如果是虚拟机需要绑定,计算机上可能有多个ip,需要接受任意一个ip的信息，给一个默认值就可以了
        std::unordered_map<std::string, sockaddr_in> onlineuser;
        pthread_mutex_t lock;
        RingQueue<std::string> rq;
        Thread *c;
        Thread *p;

    public:
        UdpServer(uint16_t port = default_port) : port_(port)
        {
            std::cout << "server addr:" << port_ << std::endl;
            pthread_mutex_init(&lock, nullptr);

            p = new Thread(1, std::bind(&UdpServer::Recv, this));
            c = new Thread(2, std::bind(&UdpServer::Broadcast, this));
        }
        void InitServer()
        {
            sock_ = socket(AF_INET, SOCK_DGRAM, 0);
            if (sock_ < 0)
            {
                std::cerr << "create socket error:" << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }
            std::cout << "create socket success:" << sock_ << std::endl;

            struct sockaddr_in local;
            bzero(&local, sizeof(local));

            local.sin_family = AF_INET;
            local.sin_port = htons(port_);
            local.sin_addr.s_addr = INADDR_ANY;

            if (bind(sock_, (struct sockaddr *)&local, sizeof(local)))
            {
                std::cerr << "bind socket error:" << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success: " << sock_ << std::endl; // 3

            p->run();
            c->run();
        }
        void addUser(const std::string &name, const struct sockaddr_in &peer)
        {
            LockGuard lockguard(&lock);
            auto iter = onlineuser.find(name);
            if (iter != onlineuser.end())
                return;

            onlineuser.insert({name, peer});
        }
        void Recv()
        {
            char buffer[1024];
            while (true)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int n = recvfrom(sock_, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
                if (n > 0)
                    buffer[n] = '\0';
                else
                    continue;

                std::cout << "recv done...." << std::endl;

                std::string clientip = inet_ntoa(peer.sin_addr);
                uint16_t clientport = ntohs(peer.sin_port);
                std::cout << clientip << "-" << clientport << "# " << buffer << std::endl;

                std::string name = clientip;
                name += "-";
                name += std::to_string(clientport);
                addUser(name,peer);

                rq.push(buffer);

                // sendto(sock_,buffer, strlen(buffer), 0, (struct sockaddr*)&peer, len);
            }
        }
        void Broadcast()
        {
            while(true)
            {
                std::string sendstring;
                rq.pop(&sendstring);
                std::vector<struct sockaddr_in> v;
                {
                    LockGuard lockguard(&lock);
                    for(auto user:onlineuser)
                    {
                        v.push_back(user.second);
                    }
                }
                for(auto user:v)
                {
                    sendto(sock_,sendstring.c_str(),sendstring.size(),0,(struct sockaddr*)&user,sizeof(user));
                    std::cout<<"send done..."<<sendstring<<std::endl;
                }
            }
        }
        ~UdpServer()
        {
            pthread_mutex_destroy(&lock);
            c->join();
            p->join();

            delete c;
            delete p;
        }
    };
}